package com.gxa.controller;

import com.gxa.common.Result;
import com.gxa.common.util.JwtUtil;
import com.gxa.domain.dto.LoginDTO;
import com.gxa.domain.entity.Employee;
import com.gxa.domain.vo.LoginVO;
import com.gxa.service.EmployeeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import com.gxa.common.annotation.RequirePermission;
import jakarta.servlet.http.HttpServletRequest;

/**
 * 用户登录控制器
 */
@Tag(name = "用户登录", description = "用户登录相关接口")
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Slf4j
public class UserController {

    private final EmployeeService employeeService;
    private final JwtUtil jwtUtil;

    @Operation(summary = "用户登录", description = "用户登录获取JWT Token，用于后续接口调用")
    @PostMapping("/login")
    public Result<LoginVO> login(@RequestBody LoginDTO loginDTO) {
        log.info("用户登录请求: {}", loginDTO.getUsername());
        
        // 验证输入参数
        if (loginDTO.getUsername() == null || loginDTO.getUsername().trim().isEmpty()) {
            return Result.error(400, "用户名不能为空");
        }
        if (loginDTO.getPassword() == null || loginDTO.getPassword().trim().isEmpty()) {
            return Result.error(400, "密码不能为空");
        }

        try {
            // 根据用户名查找员工（支持员工号或卡号）
            Employee employee = employeeService.findByUsernameOrCardNo(loginDTO.getUsername().trim());
            
            if (employee == null) {
                return Result.error(401, "用户不存在");
            }

            // 验证密码
            if (!employeeService.verifyPassword(loginDTO.getPassword(), employee.getPassword())) {
                return Result.error(401, "密码错误");
            }

            // 检查员工状态
            if (!"在职".equals(employee.getStatus())) {
                return Result.error(403, "员工已离职，无法登录");
            }

            // 生成登录信息
            LoginVO loginVO = new LoginVO();
            loginVO.setEmployeeId(employee.getEmployeeId());
            loginVO.setName(employee.getName());
            loginVO.setOperatorLevel(employee.getOperatorLevel());
            
            // 处理员工照片
            if (employee.getPhoto() != null && employee.getPhoto().length > 0) {
                String photoBase64 = java.util.Base64.getEncoder().encodeToString(employee.getPhoto());
                loginVO.setPhoto("data:image/jpeg;base64," + photoBase64);
            }
            
            // 生成JWT token
            String token = jwtUtil.generateToken(employee.getEmployeeId(), employee.getOperatorLevel());
            loginVO.setToken(token);

            log.info("用户 {} 登录成功", employee.getName());
            return Result.success(loginVO);
            
        } catch (Exception e) {
            log.error("登录异常", e);
            return Result.error(500, "登录失败，请稍后重试");
        }
    }

    @Operation(summary = "获取用户信息")
    @GetMapping("/info")
    public Result<Map<String, Object>> getUserInfo(
            @Parameter(description = "JWT Token - 请输入登录后获得的token")
            @RequestParam(required = false) String token,
            HttpServletRequest request) {
        try {
            // 优先使用查询参数中的token，如果没有则从请求头获取
            String finalToken = token;
            if (finalToken == null || finalToken.trim().isEmpty()) {
                finalToken = request.getHeader("token");
                String authorization = request.getHeader("Authorization");
                
                // 如果token为空，尝试从Authorization头获取
                if ((finalToken == null || finalToken.trim().isEmpty()) && authorization != null && authorization.startsWith("Bearer ")) {
                    finalToken = authorization.substring(7); // 去掉"Bearer "前缀
                }
            }
            
            if (finalToken == null || finalToken.trim().isEmpty()) {
                return Result.error(401, "未登录或token已过期");
            }

            // 从token中获取员工ID
            Integer employeeId = jwtUtil.getEmployeeIdFromToken(finalToken);
            if (employeeId == null) {
                log.warn("无法从token中获取员工ID: {}", finalToken);
                return Result.error(401, "Token信息不完整");
            }

            // 根据员工ID查询员工信息
            Employee employee = employeeService.getEmployeeById(employeeId);
            if (employee == null) {
                log.warn("员工不存在，员工ID: {}", employeeId);
                return Result.error(404, "员工不存在");
            }

            // 检查员工状态
            if (!"在职".equals(employee.getStatus())) {
                log.warn("员工已离职，员工ID: {}", employeeId);
                return Result.error(403, "员工已离职");
            }

            // 构建用户信息
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("name", employee.getName());
            userInfo.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            userInfo.put("employeeId", employee.getEmployeeId().toString());
            
            // 处理员工照片
            if (employee.getPhoto() != null && employee.getPhoto().length > 0) {
                String photoBase64 = java.util.Base64.getEncoder().encodeToString(employee.getPhoto());
                userInfo.put("photo", "data:image/jpeg;base64," + photoBase64);
            } else {
                userInfo.put("photo", "");
            }
            
            // 根据操作员等级设置角色
            String[] roles;
            if (employee.getOperatorLevel() != null && employee.getOperatorLevel() >= 3) {
                roles = new String[]{"admin", "employee"};
            } else {
                roles = new String[]{"employee"};
            }
            userInfo.put("roles", roles);
            
            log.info("获取用户信息成功，员工ID: {}", employeeId);
            return Result.success(userInfo);
            
        } catch (Exception e) {
            log.error("获取用户信息异常", e);
            return Result.error(500, "获取用户信息失败");
        }
    }

    @Operation(summary = "用户登出")
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success("登出成功");
    }


} 